const wxapi = require("../../../utils/wxapi");

// pages/center/recharge/recharge.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null,
    isFlag: false
  },

  /**
   * 充值
   * @param {*} e 
   */
  formSubmit(e) {
    if (this.isFlag) {
      return;
    }
    this.data.isFlag = true;
    const value = e.detail.value;
    if (!value.payMoney) {
      wx.showModal({
        title: '提示信息',
        content: '请填写充值金额。',
        showCancel: false
      })
      return;
    }
    const regex = /^[1-9]\d*$/;
    if (!regex.test(value.payMoney)) {
      wx.showModal({
        title: '提示信息',
        content: '只能充值整数数额',
        showCancel: false
      })
      return;
    }
    wx.showModal({
      title: '确认信息',
      content: `确认为卡号${this.data.userInfo.cardNo}充值金额${value.payMoney}元`,
      complete: (res) => {
        if (res.confirm) {
          // 确认充值
          const openId = wx.getStorageSync('openId');
          if (openId) {
            this.wxRecharge(openId, value.payMoney);
          } else {
            wx.login({
              success: (res) => {
                if (res.code) {
                  const jsCode = res.code;
                  const headers = {
                    'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
                  }
                  wxapi.getMiniOpenId({ jsCode }, headers).then(res => {
                    if (res.code === 20000) {
                      if (res.data) {
                        wx.setStorageSync('openId', res.data);
                        this.wxRecharge(res.data, value.payMoney);
                      } else {
                        this.data.isHandle = false;
                        wx.hideLoading()
                        this.setData({
                          isPaying: false,
                          isBargainPaying: false
                        })
                        wx.showToast({
                          title: '获取openId失败',
                          icon: 'error'
                        })
                      }
                    } else {
                      this.data.isHandle = false;
                      wx.hideLoading();
                      wx.showModal({
                        title: '提示信息',
                        content: res.message,
                        showCancel: false
                      })
                    }
                  })
                } else {
                  this.data.isHandle = false;
                  wx.showToast({
                    title: '登录失败',
                    icon: 'error',
                    success: () => {
                      this.setData({
                        isPaying: false,
                        isBargainPaying: false
                      })
                      wx.switchTab({
                        url: '/pages/index/index',
                      })
                    }
                  })
                }
              },
            })
          }
        }
        if (res.cancel) {
          this.data.isFlag = false;
        }
      }
    })
  },

  /**
   * 微信充值
   * @param {*} openId 
   * @param {*} totalAmount 
   */
  wxRecharge(openId, totalAmount) {
    const params = {
      transactionType: 0,
      productCode: "NATIVE_PAY",
      cardNo: this.data.userInfo.cardNo,
      businessTypes: "MINI_RECHARGE",
      openId,
      totalAmount
    }
    wxapi.wxMiniPayV3(params).then(res => {
      this.data.isFlag = false;
      const data = res.data;
      if (res.code === 20000) {
        wx.requestPayment({
          nonceStr: data.nonceStr,
          package: data.packageValue,
          paySign: data.paySign,
          signType: data.signType,
          timeStamp: data.timeStamp,
          success: (res) => {
            wx.showToast({
              title: '充值成功',
              success: () => {
                wx.navigateTo({
                  url: '/pages/center/center',
                })
              }
            })
          },
          fail: (res) => {
            this.data.isHandle = false;
            this.setData({
              isPaying: false,
              isBargainPaying: false,
              showBargain: false
            })
            if (res.errMsg.indexOf('fail cancel') !== -1) {
              wx.showToast({
                title: '交易取消',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '订单数据异常',
                icon: 'error'
              })
            }
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})